/****************************************************************************
** Copyright (c) quickfixengine.org  All rights reserved.
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact ask@quickfixengine.org if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/

#ifdef _MSC_VER
#include "stdafx.h"
#else
#include "config.h"
#endif
#include "CallStack.h"

#include "FixParser.h"
#include "Utility.h"
#include "FieldConvertors.h"
#include <algorithm>

namespace FIX
{
bool FixParser::extractLength( int& length, std::string::size_type& pos,
                            const std::string& buffer )
throw( MessageParseError )
{ QF_STACK_PUSH(FixParser::extractLength)

  if( !buffer.size() ) return false;

  std::string::size_type startPos = buffer.find( "\0019=", 0 );
  if( startPos == std::string::npos ) return false;
  startPos += 3;
  std::string::size_type endPos = buffer.find( "\001", startPos );
  if( endPos == std::string::npos ) return false;

  std::string strLength( buffer, startPos, endPos - startPos );

  try
  {
    length = IntConvertor::convert( strLength );
    if( length < 0 ) throw MessageParseError();
  }
  catch( FieldConvertError& )
  { throw MessageParseError(); }

  pos = endPos + 1;
  return true;

  QF_STACK_POP
}

bool FixParser::readMessage( std::string& str )
throw( MessageParseError )
{ QF_STACK_PUSH(FixParser::readMessage)

  std::string::size_type pos = 0;

  if( m_buffer.length() < 2 ) return false;
  pos = m_buffer.find( "8=" );
  if( pos == std::string::npos ) return false;
  m_buffer.erase( 0, pos );

  int length = 0;

  try
  {
    if( extractLength(length, pos, m_buffer) )
    {
      pos += length;
      if( m_buffer.size() < pos )
        return false;

      pos = m_buffer.find( "\00110=", pos-1 );
      if( pos == std::string::npos ) return false;
      pos += 4;
       pos = m_buffer.find( "\001", pos );
      if( pos == std::string::npos ) return false;
      pos += 1;
  
      str = m_buffer.substr( 0, pos );
        m_buffer.erase( 0, pos );
      return true;
    }
  }
  catch( MessageParseError& e )
  {
    if( length > 0 )
      m_buffer.erase( 0, pos + length );
    else
      m_buffer.erase();

    throw e;
  }

  return false;

  QF_STACK_POP
}
  void FixParser::readFromStream( int  m_socket) throw ( SocketRecvFailed)
  {QF_STACK_PUSH(FixParser::readFromStream)
	  //We can read without blocking
      int size = recv( m_socket, m_sockbuffer, sizeof(m_sockbuffer), 0 );
      if ( size <= 0 ) { throw SocketRecvFailed( size ); }
	  m_buffer.append(m_sockbuffer, size );
	  return;
  QF_STACK_POP
  }
  void FixParser::readFromStream( int  m_socket, sockaddr_in &addr ) throw ( SocketRecvFailed)
    {QF_STACK_PUSH(FixParser::readFromStream)
  	  //We can read without blocking
	  printf("socket:%d, addr:%p\n", m_socket, &addr);
	  socklen_t addrlen = sizeof(addr);
      int size = recvfrom( m_socket, m_sockbuffer+0, sizeof(m_sockbuffer), 0, (struct sockaddr*)&addr, &addrlen );
      printf("readFromStream:%d-size:%d", m_socket, size ); //TODO
      if ( size <= 0 ) {throw SocketRecvFailed( size );}
      m_buffer.append(m_sockbuffer, size );
  	  return;
    QF_STACK_POP
   }
  
  void FixParser::writeMessage( const std::string& str )  throw ( MessageParseError)
  {
	  m_sendQueue.push_back( str );
  }

  bool FixParser::writeToStream( int  m_socket) throw ( SocketRecvFailed )
  {
	  const iMsg& msg = m_sendQueue.front();
	  int result = send
		  ( m_socket, msg.c_str() + m_sendLength, msg.length() - m_sendLength, 0 );

	  if( result > 0 )
		  m_sendLength += result;

	  if( m_sendLength == msg.length() )
	  {
		  m_sendLength = 0;
		  m_sendQueue.pop_front();
	  }
	  return !m_sendQueue.size();
  }

  bool FixParser::writeToStream( int  m_socket, const sockaddr_in &addr) throw ( SocketRecvFailed)
   {
 	  const iMsg& msg = m_sendQueue.front();
 	  int result = sendto
 		  ( m_socket, msg.c_str() + m_sendLength, msg.length() - m_sendLength, 0,  (struct sockaddr*)&addr, (int)sizeof(addr) );

 	  if( result > 0 )
 		  m_sendLength += result;

 	  if( m_sendLength == msg.length() )
 	  {
 		  m_sendLength = 0;
 		  m_sendQueue.pop_front();
 	  }
 	  return !m_sendQueue.size();
   }
}
